<?php

namespace addons\cms\controller;

use think\Config;
use think\Validate;
use think\Exception;
use addons\cms\model\Form as FormModel;
use addons\cms\model\Fields;
use think\Db;

class Form extends Base
{

    public function save()
    {
        $token = $this->request->post('__token__');
        $info = $this->request->post();

        $info['createtime'] = time();

        try
        {
            $rule = [
                '__token__' => 'token',
            ];
            $data = [
                '__token__' => $token,
            ];
            $validate = new Validate($rule);
            $result = $validate->check($data);
            if (!$result)
            {
                throw new Exception($validate->getError());
            }

            if(!isset($info['form_id'])){
                throw new Exception("提交表单id不正确");
            }

            $form = FormModel::where('id', $info['form_id'])->find()->toArray();

            unset($info['__token__']);
            unset($info['form_id']);

            $infoArray = array();

            foreach ($info as $key => $item){
                if(is_array($item)){
                    $infoArray[$key] = implode(',', $item);
                }else{
                    $infoArray[$key] = $item;
                }
            }

            Db::name('form_'.$form['table'])->insert($infoArray);
            $this->success(__('评论成功'));
        }
        catch (Exception $e)
        {
            $this->error($e->getMessage(), null, ['token' => $this->request->token()]);
        }
    }

}
